package com.jack.payment.util.redis;


import com.jack.payment.constant.RedisConstant;
import com.jack.payment.entity.common.BusinessException;
import com.jack.payment.util.common.StringUtil;
import com.jack.payment.util.common.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GenerateId {
    private Logger log = LoggerFactory.getLogger(GenerateId.class);
    // 设置过期时间 -1 为永不过期
    private static final Long EXPIRE_TIME = -1L;
    // 设置默认起始数值为0
    private static final Long INIT_START_COUNT = 0L;
    /**  默认过期时长，单位：秒 */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24 * 7;



    @Autowired
    private RedisUtil redisUtil;

    /**
     * 设置用户的id
     * @return
     */
    public String generateUserId() throws BusinessException {
        String userId = String.valueOf(TimeUtil.getCurrentTime())
                + redisUtil.incrementOne(RedisConstant.USER_GENERATE_ID, INIT_START_COUNT,  EXPIRE_TIME);;
        if (StringUtil.isEmpty(userId)) {
            throw new BusinessException();
        }
        return userId;
    }

    /**
     * 设置订单id
     * @return
     */
    public String generateOrderId() throws BusinessException {
        String orderId = "NO" + TimeUtil.getSimpleCurrentData() +
                redisUtil.incrementOne(RedisConstant.ORDER_GENERATE_ID, INIT_START_COUNT, DEFAULT_EXPIRE);
        if (StringUtil.isEmpty(orderId)) {
            throw new BusinessException();
        }
        return orderId;
    }

    /**
     * 设置消息队列id
     * @return
     */
    public String generateMQId() throws BusinessException {
        String mqId = TimeUtil.getSimpleCurrentData() +
                redisUtil.incrementOne(RedisConstant.MESSAGE_GENERATE_ID, INIT_START_COUNT, DEFAULT_EXPIRE);
        if (StringUtil.isEmpty(mqId)) {
            throw new BusinessException();
        }
        return mqId;
    }
}
